package com.xhg.mqtt.listener;

import com.xhg.mqtt.cache.CacheManagerImpl;
import com.xhg.mqtt.constant.MqttConstants;
import com.xhg.mqtt.constant.MsgConstants;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * 监听缓存失效数据
 *
 * @author E.T
 * @version 1.0
 * @Description
 * @date 2018-08-20 14:26
 * @updateby
 * @updatedate
 * @since 1.0
 */
public class CacheListener {

    private CacheManagerImpl cacheManagerImpl = new CacheManagerImpl();

    private CacheListener() {
    }

    private static class CacheListenerHolder {

        private final static CacheListener instance = new CacheListener();
    }

    public static CacheListener getInstance() {
        return CacheListenerHolder.instance;
    }

    public CacheManagerImpl getCacheManager() {
        return cacheManagerImpl;
    }

    public void startListen() {
        //死循环对终端资源消耗比较大，改为定时器
//        Executors.newSingleThreadExecutor().execute(() -> {
//            Thread.currentThread().setName("缓存监听线程");
//            for (; ; ) {
//                //监测缓存清理
//                for (String key : cacheManagerImpl.getAllKeys()) {
//                    if (cacheManagerImpl.isTimeOut(key)) {
//                        cacheManagerImpl.clearByKey(key);
//                        MqttLoggerFactory.info(key + MsgConstants.CACHE_CLEAN);
//                    }
//                }
//            }
//        });

        ScheduledExecutorService service = Executors
            .newScheduledThreadPool(1,
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "缓存监听定时器");
                    }
                });
        service.scheduleAtFixedRate(() -> {
            for (String key : cacheManagerImpl.getAllKeys()) {
                if (cacheManagerImpl.isTimeOut(key)) {
                    cacheManagerImpl.clearByKey(key);
                    MqttLoggerFactory.info(key + MsgConstants.CACHE_CLEAN);
                }
            }
        }, MqttConstants.INIT_START, 30, TimeUnit.SECONDS);

    }
}
